package juc.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

public class MyLockTest {
    static CountDownLatch downLatch = new CountDownLatch(1);
    public static void main(String[] args) throws InterruptedException {
        MyLock lock = new MyLock();

        Thread t1 = new Thread(() -> {handle(lock);}, "Thread-1");
        Thread t2 = new Thread(() -> {handle(lock);}, "Thread-2");
        Thread t3 = new Thread(() -> {handle(lock);}, "Thread-3");

        t1.start();
        t2.start();
        t3.start();

        TimeUnit.SECONDS.sleep(1);
        downLatch.countDown();
        TimeUnit.SECONDS.sleep(5);
    }
    private static void handle(Lock lock) {
        try {
            downLatch.await();
            System.out.println(Thread.currentThread().getName() + ",---开始抢锁---");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到锁");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "释放锁");
        } finally {
            lock.unlock();
        }
    }

}
